package com.flowershop.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.flowershop.entity.Flower;
import com.flowershop.service.FlowerService;

@RestController
@RequestMapping("/api/flowers")
@CrossOrigin
public class FlowerController {

    @Autowired
    private FlowerService flowerService;

    @GetMapping("/page")
    public Page<Flower> page(@RequestParam(defaultValue = "1") Integer current,
                           @RequestParam(defaultValue = "10") Integer size,
                           @RequestParam(required = false) String name,
                           @RequestParam(required = false) String category) {
        Page<Flower> page = new Page<>(current, size);
        LambdaQueryWrapper<Flower> queryWrapper = new LambdaQueryWrapper<>();
        if (name != null && !name.isEmpty()) {
            queryWrapper.like(Flower::getName, name);
        }
        if (category != null && !category.isEmpty()) {
            queryWrapper.eq(Flower::getCategory, category);
        }
        return flowerService.page(page, queryWrapper);
    }

    @GetMapping("/{id}")
    public Flower getById(@PathVariable Long id) {
        return flowerService.getById(id);
    }

    @PostMapping
    public Flower save(@RequestBody Flower flower) {
        flowerService.save(flower);
        return flower;
    }

    @PutMapping
    public Flower update(@RequestBody Flower flower) {
        flowerService.updateById(flower);
        return flower;
    }

    @DeleteMapping("/{id}")
    public boolean delete(@PathVariable Long id) {
        return flowerService.removeById(id);
    }

    @PutMapping("/{id}/stock")
    public boolean updateStock(@PathVariable Long id, @RequestParam Integer quantity) {
        return flowerService.updateStock(id, quantity);
    }
} 